#!/bin/bash

# Copyright 2015 The Bazel Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

set -eu

TEST_APP_DIR="$(mktemp -d -t test_app_dir)"
unzip -qq -d "${TEST_APP_DIR}" "%(test_app_ipa)s"
TEST_APP_DIR="${TEST_APP_DIR}/Payload/%(test_app_name)s.app"

XCTEST_APP_DIR="$(mktemp -d -t xctest_app_dir)"
unzip -qq -d "${XCTEST_APP_DIR}" "%(xctest_app_ipa)s"
XCTEST_APP_DIR="${XCTEST_APP_DIR}/Payload/%(xctest_app_name)s.app"

killall "iOS Simulator" >/dev/null 2>/dev/null || :

SIMHOME="$(mktemp -d -t simhome)"

LOGFILE="$(mktemp -t logfile)"

SIMULATOR_PLATFORM="$(/usr/bin/xcrun --sdk iphonesimulator --show-sdk-platform-path)"
SIMULATOR_DEV_LIBRARY="$SIMULATOR_PLATFORM/Developer/Library"

"%(iossim_path)s" \
    -u "${SIMHOME}" \
    -d "%(device_type)s" \
    -s "%(simulator_sdk)s" \
    -t 60 \
    -e DYLD_INSERT_LIBRARIES="$SIMULATOR_DEV_LIBRARY/PrivateFrameworks/IDEBundleInjection.framework/IDEBundleInjection" \
    -e "XCInjectBundle=${TEST_APP_DIR}" \
    -e "XCInjectBundleInto=${XCTEST_APP_DIR}" \
    -e DYLD_FALLBACK_FRAMEWORK_PATH="$SIMULATOR_DEV_LIBRARY/Frameworks" \
    "${XCTEST_APP_DIR}" \
    -NSTreatUnknownArgumentsAsOpen NO \
    -ApplePersistenceIgnoreState YES \
    -XCTest All \
    "${TEST_APP_DIR}" \
    2>&1 | tee "${LOGFILE}"

killall "iOS Simulator" >/dev/null 2>/dev/null || :

# TODO(danielwh): Much better support for detecting failures. Actually parse the log.
if grep -q "with [1-9].* failure" "${LOGFILE}"; then
  exit 1
fi
